<template>
  <ex-dialog
    width="1000px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    @closeDialog="handleClose"
  >	
      <el-form ref="form" :model="form"  label-width="150">
				<el-form-item label="推荐店铺:">
					<el-select v-model="form.shopIdList" placeholder="请选择" ref="elSelect" reserve-keyword  multiple filterable value-key="shopId" @focus="handlFocus" @change="changePunchActivityId"  :filter-method="filterValue">
						<el-option v-for="item in goodsList"  :key="item.shopId" :label="item.shopName" :value="item" >
						</el-option>
					</el-select>
					<el-button size="mini" type="primary" @click="confirm" style="margin-left: 20px" >确定</el-button>
				</el-form-item>
        <el-form-item label="" prop="">
          <el-table :data="tabelList" v-loading="loading" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.6)" element-loading-text="加载中" stripe border >
            <el-table-column label="序号" align="center" type="index" width="64px" />
            <el-table-column label="店铺名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
            <el-table-column label="可售预付卡种类" align="center" prop="assetNum" :show-overflow-tooltip="true" />
            <el-table-column label="排序" align="center" width="160px">
              <template slot-scope="scope" >
                <el-button size="mini" type="text" @click="orderClick(0,scope.$index)" v-if="scope.$index != 0">上移</el-button>
                <el-button size="mini" type="text" @click="orderClick(1,scope.$index)" v-if="scope.$index < tabelList.length - 1">下移</el-button>
                <el-button size="mini" type="text" @click="orderClick(2,scope.$index)">置顶</el-button>
                <el-button size="mini" type="text" @click="orderClick(3,scope.$index)">置底</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="deleteView(scope.$index,scope.row.shopId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="sumitLoading">保存提交</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
  </ex-dialog>
</template>

<script>
  import {
    addMerchantShopRecommend,
    merchantShopSelectList,
    merchantShopRecommendList,
  } from '@/api/clientManagement/businessSetting'
  import {
   adminDict,
  } from "@/api/clientManagement";
  export default {
    // dicts: ['asset_card_type'],
    name: "Dialog",
    props: {
			visible: Boolean,
			id: String,
			pathType: String,
    },
    data() {
      return {
				sumitLoading: false,
				loading: false,
        title: "添加推荐商家",
        goodsList: [], //物品选择列表
        tabelList: [],
        filterShopIdList:[],
        shopName:'',
        areaCode:'',
        form: {
          shopIdList: [], 
        },
      };
    },
    created() {
      this.getInfo()
      this.getlinkagelist()
    },
    methods: {
      async filterValue(query){
        if(query !== ""){
            this.shopName = query
            await this.getGoods()
        }else{
            this.shopName = ''
            await this.getGoods()
        }
      },
      handlFocus(e){
        this.shopName = this.$refs['elSelect'].query
        this.getGoods()
      },
      getlinkagelist() {
      //获取字典
      const params = {
        dictType: "merchant_enter_area",
      };
      adminDict(params).then((res) => {
        var typeLs = res.result[0].dictList;
        this.areaCode = typeLs[0].id;
      });
    },
      //获取推荐商家下拉
     async getGoods(){
        var params = {
          filterShopIdList:this.filterShopIdList,
          shopName:this.shopName
        }
        var res = await merchantShopSelectList(params)
            this.goodsList = res.result    
      },
      //获取推荐商家配置
      getInfo(){
        merchantShopRecommendList().then(res => {
          var data  = res.result
          this.filterShopIdList = []
          data.forEach(item => {
            this.filterShopIdList.push(item.shopId)
          })
          // console.log(this.filterShopIdList)
          this.getGoods()
          this.tabelList = data
        })
      },
      changePunchActivityId(item){
        //  console.log(item)
        //  this.tabelList.push(item)
        //  this.filterShopIdList.push(item.shopId)
        //  this.form.shopIdList = []
        //  this.getGoods()
      },
      confirm(){
          if(this.form.shopIdList.length == 0){
            this.$message.error('请选择');
            return
          }
          this.tabelList = [
            ...this.tabelList,
            ...this.form.shopIdList
          ]
          // 返回某个字段的集合
          var shopIdList =  this.form.shopIdList.reduce((pre, el, index) => {
              pre.push(el.shopId);
              return pre;
            }, []);
            this.filterShopIdList = [
              ...this.filterShopIdList,
              ...shopIdList
            ]
          this.form.shopIdList = []

      },
			//取消
			handleClose(formName) {
				this.$emit('update:visible', false)
				this.reset();
      },
      reset(){
        this.$refs['form'].resetFields();
      },
			//确认
			handleConfirm(){
				this.$emit('success')
			},
      /** 删除提交按钮deleteWhite */
      deleteView(index,id) {
        console.log(index,id)
        var that = this
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tabelList.splice(index,1)
          var indexOf4 = (this.filterShopIdList || []).findIndex((item) => item === id);
          this.filterShopIdList.splice(indexOf4,1)
        }).catch(() => {});
      },
      /** 执行按钮 */
       submitForm() {
           this.sumitLoading = true;
           var data = {
              areaCode: this.areaCode,
              recommendList:this.tabelList
            }
            addMerchantShopRecommend(data).then(response => {
              setTimeout(()=>{
                this.$message.success('执行成功');
                this.sumitLoading = false;
                this.handleClose();
                this.$emit('success')
              },1000)
            }).catch(() => {
              this.sumitLoading = false;
            });
			},
      //上移、下移、置顶、置底
      orderClick(type, i) {
        
        // 深度拷贝原数组，因为下面会使用 splice 方法，避免影响原数组
        let arr = [...this.tabelList];
              // 默认下标 0
        let index = 0;
              // 判断
        switch (type) {
          case 0: {// 上移
            index = i === 0 ? i : (i - 1);
            break;
          }
          case 1: {// 下移
            index = i === arr.length - 1 ? i : (i + 1);
            break;
          }
          case 2: {// 置顶
            index = 0;
            break;
          }
          case 3: {// 置底
            index = arr.length - 1;
            break;
          }
        }
        // 先删除原有
        let item = arr.splice(i, 1);
        // 再删除新地方
        arr.splice(index, 0, item[0]);
        this.tabelList = arr;
      },
    }
  };

</script>
<style scoped>
  .main {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px;
  }

  .icon_yes {
    font-size: 28px;
    color: #67c23a;
  }
  .el-select{
    width: 640px;
  }
  .el-button{
    margin: 0 20px;
  }
</style>
